﻿using System;
using System.IO;
using System.Web;

namespace AT.IBMS.Framework.Tools
{
    public static class UrlTool
    {

        /// <summary>
        /// 检索虚拟路径（绝对的或相对的）或应用程序相关的路径映射到的物理路径。
        /// </summary>
        /// <param name="virtualPath">表示虚拟路径的 String。</param>
        /// <returns>与虚拟路径或应用程序相关的路径关联的物理路径。</returns>
        public static string MapPath(this Tool t, string virtualPath)
        {

            string result;

            if (string.IsNullOrEmpty(virtualPath))
            {
                throw new ArgumentNullException("virtualPath");
            }

            if (HttpContext.Current != null)
            {
                result = HttpContext.Current.Server.MapPath(virtualPath);
            }
            else
            {

                result = virtualPath.Replace("/", "");
                result = result.Replace("~", "");

                if (result.StartsWith("\\"))
                {
                    result = result.TrimStart('\\');
                }

                result = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, result);

            }

            return result;

        }

        /// <summary>
        /// 移除Url中的全部参数
        /// </summary>
        /// <param name="url">原始Url</param>
        /// <returns></returns>
        public static string RemoveUrlParameters(this Tool t, string url)
        {
            string cleanUrl = string.Empty;
            if (url != string.Empty)
            {
                string[] urlArray = url.ToLower().Split(new string[] { "?" }, StringSplitOptions.RemoveEmptyEntries);
                cleanUrl = urlArray[0];
            }
            return cleanUrl;
        }

        /// <summary>
        /// 根据redirectUrl参数，生成一个新的url。
        /// 这个新的url带有一个ReturnUrl参数，这个参数为当前请求地址的url。
        /// </summary>
        /// <param name="redirectUrl"></param>
        /// <returns></returns>
        public static string GetAutoRedirectUrl(this Tool t, string redirectUrl)
        {

            string url;
            int index;
            string returnUrl;

            url = redirectUrl;

            if (url.IndexOf('?') >= 0)
            {
                url = RemoveQueryStringVariableFromUrl(t, url, "ReturnUrl");
            }

            index = url.IndexOf('?');

            if (index < 0)
            {
                url = url + "?";
            }
            else if (index < (url.Length - 1))
            {
                url = url + "&";
            }

            returnUrl = HttpUtility.UrlEncode(HttpContext.Current.Request.Url.PathAndQuery, HttpContext.Current.Request.ContentEncoding);

            url = url + "ReturnUrl=" + returnUrl;

            return url;

        }

        /// <summary>
        /// 移除指定的参数。
        /// </summary>
        /// <param name="strUrl"></param>
        /// <param name="QSVar"></param>
        /// <returns></returns>
        public static string RemoveQueryStringVariableFromUrl(this Tool t, string strUrl, string QSVar)
        {
            int index = strUrl.IndexOf('?');
            if (index >= 0)
            {
                string sep = "&";
                string str2 = "?";
                string token = sep + QSVar + "=";
                RemoveQSVar(ref strUrl, index, token, sep, sep.Length);
                token = str2 + QSVar + "=";
                RemoveQSVar(ref strUrl, index, token, sep, str2.Length);
                sep = HttpUtility.UrlEncode("&");
                str2 = HttpUtility.UrlEncode("?");
                token = sep + HttpUtility.UrlEncode(QSVar + "=");
                RemoveQSVar(ref strUrl, index, token, sep, sep.Length);
                token = str2 + HttpUtility.UrlEncode(QSVar + "=");
                RemoveQSVar(ref strUrl, index, token, sep, str2.Length);
            }
            return strUrl;
        }

        private static void RemoveQSVar(ref string strUrl, int posQ, string token, string sep, int lenAtStartToLeave)
        {
            for (int i = strUrl.LastIndexOf(token, StringComparison.Ordinal); i >= posQ; i = strUrl.LastIndexOf(token, StringComparison.Ordinal))
            {
                int startIndex = strUrl.IndexOf(sep, i + token.Length, StringComparison.Ordinal) + sep.Length;
                if ((startIndex < sep.Length) || (startIndex >= strUrl.Length))
                {
                    strUrl = strUrl.Substring(0, i);
                }
                else
                {
                    strUrl = strUrl.Substring(0, i + lenAtStartToLeave) + strUrl.Substring(startIndex);
                }
            }
        }

    }
}
